/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/commons/json/serializer/DateFormatSerializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: DateFormatSerializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (Mon, 02 Jul 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.commons.json.serializer;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;

/**
 * @author elancom
 */
public class DateFormatSerializer implements ObjectSerializer {

	public final static DateFormatSerializer instance = new DateFormatSerializer();

	@Override
	public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType) throws IOException {
		final SerializeWriter out = serializer.getWriter();

		if (object == null) {
			out.writeNull();
			return;
		}

		final String pattern = ((SimpleDateFormat) object).toPattern();

		if (out.isEnabled(SerializerFeature.WriteClassName)) {
			if (object.getClass() != fieldType) {
				out.write('{');
				out.writeFieldName("@type");
				serializer.write(object.getClass().getName());
				out.writeFieldValue(',', "val", pattern);
				out.write('}');
				return;
			}
		}

		out.writeString(pattern);
	}
}
